const { login } = require("../controller/user");
const { SuccessModel, ErrorModel } = require("../model/resModel");
const router = require('express').Router()

router.post('/login', (req, res, next) => {
  const { userName, userPass } = req.body;
  if (!userName) {
    res.json(new ErrorModel("用户名不能为空"))
  }
  if (!userPass) {
    res.json(new ErrorModel("密码不能为空"))
  }
  login(userName, userPass).then(data => {
    if (data) {
      if (data.username) {
        req.session.userName = data.username;
      }
      if (data.isadmin) {
        req.session.isAdmin = 1;
      }
      res.json(new SuccessModel("登录成功"));
    } else {
      res.json(new ErrorModel("登录失败"));
    }
  })
})
router.get('/login-test', (req, res, next) => {
  if (req.session.userName) {
    res.json(new SuccessModel("登录成功"));
  } else {
    res.json(new ErrorModel('尚未登录'))
  }
})
router.get('/login-out', (req, res, next) => {
  req.session.userName = null;
  req.session.isAdmin = null;
  res.json(new SuccessModel("退出成功"));
})

module.exports = router